<script setup lang="ts">
import { onMounted, ref } from "vue";
import axios from 'axios';
import {ElMessage, ElMessageBox} from 'element-plus';
import { useRouter } from 'vue-router';

// 工具函数：从Token解析用户ID（根据实际Token结构调整字段）
const getUserIdFromToken = (token: string) => {
  if (!token) return '';
  try {
    const payloadBase64 = token.split('.')[1];
    const decoded = JSON.parse(atob(payloadBase64));
    return decoded.sub; // 假设用户ID存放在JWT的sub字段
  } catch (error) {
    console.error('Token解析失败:', error);
    return '';
  }
};

// 存储用户数据
const userList = ref({});
const loading = ref(false);
const router = useRouter();

onMounted(() => {
  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.warning('未检测到登录态，请先登录');
    return;
  }
  const userId = getUserIdFromToken(token);
  if (!userId) {
    ElMessage.warning('Token无效，无法获取用户信息');
    return;
  }

  // 请求用户信息（使用Token解析的userId）
  axios.get('http://localhost:8020/user/GetUserInfo', {
    params: { userId }
  })
      .then(res => {
        userList.value = res.data;
        console.log('用户信息加载成功：', userList.value);
      })
      .catch(err => {
        ElMessage.error('获取用户信息失败');
        console.error('错误详情：', err);
      });
});

// 触发文件选择
const triggerFileSelect = () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*';
  input.onchange = (e) => {
    const file = (e.target as HTMLInputElement).files?.[0];
    if (file) {
      handleAvatarUpload(file);
    }
  };
  input.click();
};

// 处理头像上传
const handleAvatarUpload = async (file: File) => {
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件');
    return;
  }
  // 验证文件大小（5MB以内）
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB');
    return;
  }

  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.warning('未登录，请先登录');
    return;
  }
  const userId = getUserIdFromToken(token);
  if (!userId) {
    ElMessage.warning('Token解析失败，无法上传头像');
    return;
  }

  loading.value = true;
  try {
    const formData = new FormData();
    formData.append('image', file);
    formData.append('userId', userId); // 使用Token解析的userId

    const res = await axios.post(
        'http://localhost:8020/user/uploadAvatar',
        formData,
        {
          headers: {
            'Authorization': `Bearer ${token}`, // 携带Token验证
          }
        }
    );

    // 更新头像显示
    userList.value.avatar = res.data.data;
    ElMessage.success('头像更新成功');
  } catch (error) {
    ElMessage.error('头像上传失败');
    console.error('上传错误:', error);
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <div style="background: #CCCCCC;">
    <div style="background: white;">
      <el-affix :offset-top="0" :z-index="999">
        <el-col :span="24" style="background: white">
            <el-icon :size="20" @click="$router.back()" style="color: black; margin: 8px;">
              <ArrowLeftBold />
            </el-icon>
        </el-col>
      </el-affix>
      <!-- 头像 -->
      <div style="margin-top: 8px;border-bottom: 1px solid #f0f0f0;">
        <el-row style="height: 50px; background: white; display: flex; align-items: center;">
          <el-col :span="16">
            <div style="height: 50px; display: flex; align-items: center; margin-left: 5px;">
              <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">头像</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div style="text-align: right;margin-right: 15px">
              <div @click="triggerFileSelect" style="cursor: pointer; display: inline-block;">
                <el-loading v-if="loading" indicator-color="#409EFF" size="small"></el-loading>
                <img
                    v-if="!userList.avatar"
                    src="@/assets/icon/微信头像.svg"
                    alt="默认头像"
                    style="width: 30px; margin-left: 10px"
                />
                <el-image
                    v-else
                    :src="userList.avatar"
                    style="width: 30px; margin-left: 10px"
                    alt="用户头像"
                ></el-image>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 名字 -->
      <div style="margin-top: 8px;border-bottom: 1px solid #f0f0f0;">
        <el-row style="height: 50px; background: white; display: flex; align-items: center;">
          <el-col :span="16">
            <div style="height: 50px; display: flex; align-items: center; margin-left: 5px;">
              <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">名字</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div style="text-align: right;margin-right: 15px">{{ userList.username }}</div>
          </el-col>
        </el-row>
      </div>

      <!-- 性别 -->
      <div style="margin-top: 8px;border-bottom: 1px solid #f0f0f0;">
        <el-row style="height: 50px; background: white; display: flex; align-items: center;">
          <el-col :span="16">
            <div style="height: 50px; display: flex; align-items: center; margin-left: 5px;">
              <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">性别</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div style="text-align: right;margin-right: 15px">
              {{ userList.gender === 1 ? '男' : (userList.gender === 2 ? '女' : '') }}
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 地区 -->
      <div style="margin-top: 8px;border-bottom: 1px solid #f0f0f0;">
        <el-row style="height: 50px; background: white; display: flex; align-items: center;">
          <el-col :span="16">
            <div style="height: 50px; display: flex; align-items: center; margin-left: 5px;">
              <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">地区</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div style="text-align: right;margin-right: 15px">{{ userList.region }}</div>
          </el-col>
        </el-row>
      </div>

      <!-- 手机号 -->
      <div style="margin-top: 8px;border-bottom: 1px solid #f0f0f0;">
        <el-row style="height: 50px; background: white; display: flex; align-items: center;">
          <el-col :span="16">
            <div style="height: 50px; display: flex; align-items: center; margin-left: 5px;">
              <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">手机号</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div style="text-align: right;margin-right: 15px">{{ userList.phone }}</div>
          </el-col>
        </el-row>
      </div>

      <!-- 微信号 -->
      <div style="margin-top: 8px;border-bottom: 1px solid #f0f0f0;">
        <el-row style="height: 50px; background: white; display: flex; align-items: center;">
          <el-col :span="16">
            <div style="height: 50px; display: flex; align-items: center; margin-left: 5px;">
              <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">微信号</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div style="text-align: right;margin-right: 15px">{{ userList.wechat_number }}</div>
          </el-col>
        </el-row>
      </div>

      <!-- 我的二维码 -->
      <div style="margin-top: 8px;border-bottom: 1px solid #f0f0f0;">
        <el-row style="height: 50px; background: white; display: flex; align-items: center;">
          <el-col :span="16">
            <div style="height: 50px; display: flex; align-items: center; margin-left: 5px;">
              <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">我的二维码</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div style="text-align: right;margin-right: 15px">
              <img src="@/assets/icon/二维码.svg" alt="图标" style="width: 30px;margin-left: 10px" />
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 拍一拍 -->
      <div style="margin-top: 8px;border-bottom: 1px solid #f0f0f0;">
        <el-row style="height: 50px; background: white; display: flex; align-items: center;">
          <el-col :span="16">
            <div style="height: 50px; display: flex; align-items: center; margin-left: 5px;">
              <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">拍一拍</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 签名 -->
      <div style="margin-top: 8px;">
        <el-row style="height: 50px; background: white; display: flex; align-items: center;">
          <el-col :span="16">
            <div style="height: 50px; display: flex; align-items: center; margin-left: 5px;">
              <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">签名</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div style="text-align: right;margin-right: 15px">{{ userList.signature }}</div>
          </el-col>
        </el-row>
      </div>
    </div>

    <div style="margin-top: 8px;">
      <el-row style="height: 50px; background: white; display: flex; align-items: center;">
        <el-col :span="16">
          <div style="height: 50px; display: flex; align-items: center; margin-left: 5px;">
            <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">来电铃声</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div style="text-align: right;margin-right: 15px">片头音乐</div>
        </el-col>
      </el-row>
    </div>

    <div>
      <!-- 我的地址 -->
      <div style="margin-top: 8px;border-bottom: 1px solid #f0f0f0;">
        <el-row style="height: 50px; background: white; display: flex; align-items: center;">
          <el-col :span="16">
            <div style="height: 50px; display: flex; align-items: center; margin-left: 5px;">
              <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">我的地址</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 我的发票抬头 -->
      <div>
        <el-row style="height: 50px; background: white; display: flex; align-items: center;">
          <el-col :span="16">
            <div style="height: 50px; display: flex; align-items: center; margin-left: 5px;">
              <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">我的发票抬头</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 微信豆 -->
    <div style="margin-top: 8px;">
      <el-row style="height: 50px; background: white; display: flex; align-items: center;">
        <el-col :span="16">
          <div style="height: 50px; display: flex; align-items: center; margin-left: 5px;">
            <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">微信豆</span>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 修改 -->
    <div style="margin-top: 8px;">
      <el-row style="height: 50px; background: white;">
        <el-col :span="24">
          <div style="height: 50px; display: flex; align-items: center; justify-content: center;">
            <span
                style="font-size: 17px; font-weight: bold;color: red; cursor: pointer;"
                @click="router.push({ name: 'Modification' })"
            >
              修改
            </span>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style scoped>

</style>